<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgencyModel;
use app\common\model\MoneyLog;
use app\common\model\OrderAudit;
use app\common\model\OrderMore;
use app\common\model\Packages;
use app\common\model\UserPackagesConfig;
use fast\Random;
use think\db\Query;
use think\Validate;

/**
 * 创建订单
 */
class Order extends Api
{
    /**
     * Packages模型对象
     * @var \app\common\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order();
    }

    protected $noNeedLogin = [
        'callback',
        'add',
        'orderSync',
        'callbackTwo',
        'callbackGth',
        'cse',
        'orderInfo',
        'purchase',
        'kgjcreateOrder'
    ];
    protected $noNeedRight = ['*'];

    //订单列表
    public function index()
    {
        $status             = input('status', '');
        $order_type         = input('order_type', 1);
        $where['is_agency'] = 2;
        if ($status == 5) {
            $order_type = 2;
        }
        $ids                    = input('ids');
        $agencyWhere['status']  = 1;
        $agencyWhere['user_id'] = $this->auth->id;
        if ($ids) {
            $agencyWhere['user_id'] = $ids;
        }
        $agency = AgencyModel::where($agencyWhere)->find();
        if ($order_type == 2) {
            if (!empty($agency['type'])) {
                if ($agency['type'] == 2) {
                    $where['agency_area_id'] = $agency['user_id'];
                } else {
                    $where['plot_id'] = $agency['user_id'];
                }
            }
        } else {
            $where['user_id'] = $this->auth->id;
            if ($ids) {
                $where['user_id'] = $ids;
            }
        }

        if ($status >= 0) {
            if ($status == 4 || $status == 5 || $status == 6) {
                $where['order_status'] = ['gt', 3];
            } else {
                $where['order_status'] = $status;
            }
        }
        $query = $this->model->where($where);
//        if ($status == 4) {
//            $query->where('order_status', '<', 6);
//        }
        $package_name = input('package_name');
        if ($package_name) {
            $query = $query->where(['package_name' => ['like', '%'.$package_name.'%']]);
        }
        $shipping_phone = input('shipping_phone');
        if ($shipping_phone) {
            $query = $query->where(['shipping_phone' => $shipping_phone]);
        }
        $phone = input('phone');
        if ($phone) {
            $query = $query->where(['phone' => $phone]);
        }
        $shipping_contact = input('shipping_contact');
        if ($shipping_contact) {
            $query = $query->where(['shipping_contact' => $shipping_contact]);
        }
        $sta_time = input('sta_time');
        $end_time = input('end_time');

        if ($sta_time && $end_time) {
            $sta_time = strtotime($sta_time.' 00:00:01');
            $end_time = strtotime($end_time.' 23:59:59');
            $query    = $query->where('createtime', 'between time', [$sta_time, $end_time]);
        }


        $data = $query->with(['packages'])->order('id desc')->paginate()->each(function ($query) use (
            $order_type,
            $agency,
            $status,
            $ids
        ) {
            $baoxiao_money = MoneyLog::where(['order_id' => $query->id, 'memo' => '话费报销'])->value('money');
            $logInfo       = MoneyLog::where(['order_id' => $query->id, 'memo' => '话费报销'])->find();
            if ($logInfo) {
                $baoxiao_money = $logInfo['money'];
            }
            if ($query->jiesuan_time_text || $query->order_status == 5) {
                if ($agency) {
                    if ($agency->type == 2) {
                        $level = 4;
                    } else {
                        $level = 5;
                    }
                }

                if ($order_type == 2 && $agency || $status == 5) {
                    if ($query->is_more == 1) {
                        if ($agency->type == 2) {
                            $money = $query->packages->pplots_profit;
                        } else {
                            $money = $query->packages->pplots_yunying_profit;
                        }
                    } else {
                        $user_id = $agency['user_id'];
                        $money   = OrderMore::where([
                            'user_id'  => $user_id,
                            'order_id' => $query->id,
                            'level'    => $level
                        ])->order('id asc')->value('money');
                    }
                    $query->user_rebate = $money;
                } else {
                    if ($query->is_more == 1) {
                        $money = $query->packages->one_commission;
                    } else {
                        $money = OrderMore::where([
                            'user_id'  => $query->user_id,
                            'order_id' => $query->id,
                        ])->order('id asc')->value('money');
                    }
                    $query->user_rebate = $money;
                }
            }
            if ($query->order_status == 4) {
                if ($query->is_more == 1) {
                    if ($status == 4) {
                        if ($ids) {
                            $money = $query->packages->junior_contribution;
                        } else {
                            $money = $query->packages->one_commission;
                        }
                    } else {
                        if ($order_type && $agency) {
                            if ($agency->type == 2) {
                                $money = $query->packages->pplots_profit;
                            } else {
                                $money = $query->packages->pplots_yunying_profit;
                            }
                        } else {
                            $money = $query->packages->one_commission;
                        }
                    }
                    $bao_mobey = '左右一次性报销话费'.bcadd($query->packages->ciyue_set_meal,
                            $query->packages->bxhf_text);
                    $msg       = '一次性';
                } else {
                    $level = 1;
                    if ($agency && $order_type || $status == 5) {
                        $user_id = $agency['user_id']??0;
                        if ($agency['type'] == 2) {
                            $level = 4;
                        } else {
                            $level = 5;
                        }
                    } else {
                        $user_id = $this->auth->id;
                    }
                    if ($status == 4) {
                        if ($ids) {
                            $level   = 2;
                            $user_id = $this->auth->id;
                        }
                    }

                    $money     = OrderMore::where([
                        'user_id'  => $user_id,
                        'order_id' => $query->id,
                        'level'    => $level,
                    ])->order('id asc')->value('money');
                    $bao_mobey = '左右报销首月实付套餐费'.$query->packages->bxhf_text;
                    $msg       = '首月';
                }
                if ($query->packages->day != 6) {
                    if ($query->audit_time) {
                        $audit_time = $query->audit_time;
                    } else {
                        $audit_time = $query->audit_upload_time;
                    }
                    $time = 7 * 86400 + $audit_time;
                } else {
                    $time = settlement_time($query->audit_time ? $query->audit_time : $query->audit_upload_time);
                }
                $query->user_rebate           = $money;
                $query->jiesuan_time_text_two = '本单将于'.date('Y-m-d', $time).'左右'.$msg.'结算佣金'.$money.'元。';
                $query->baoxiao_msg_text      = '本单将于'.date('Y-m-d', $time).$bao_mobey.'元。';
            }
            if ($query->order_status == 5) {
                if ($query->is_more == 1) {
//                    $query->jiesuan_time_text_two = '本单已于'.date('Y-m-d',$query->settlement_time).'结算全部佣金'.$query->user_rebate.'元';
//                    $query->baoxiao_msg_text      = '本单已于'.date('Y-m-d',$query->baoxiao_time).'完成全部话费报销'.$baoxiao_money.'元。';
                    $query->jiesuan_time_text_two = '';
                    $query->baoxiao_msg_text      = '';
                } else {
                    if ($query->more_num == 1) {
                        if ($status == 6) {
                            $query->baoxiao_msg_one_text = '本单已于'.date('Y-m-d',
                                    $query->baoxiao_time).'完成首月话费报销'.$baoxiao_money.'元。';
                            $query->baoxiao_msg_text     = '本单将于'.date('Y-m-d',
                                    $query->two_js_time).'左右报销次月话费'.$query->packages->ciyue_set_meal.'元。';
                        } else {
                            $level = 1;
                            if ($ids) {
                                $user_id = $this->auth->id;
                                $level   = 2;
                            } else {
                                if ($status == 5 && $agency) {
                                    $user_id = $agency['user_id'];
                                    if ($agency['type'] == 2) {
                                        $level = 4;
                                    } else {
                                        $level = 5;
                                    }
                                } else {
                                    $user_id = $query->user_id;
                                }
                            }
                            $where = [
                                'user_id'  => $user_id,
                                'order_id' => $query->id,
                                'status'   => 1,
                                'level'    => $level
                            ];
                            $money = OrderMore::where($where)->order('id desc')->value('money');
                            $time  = 0;
                            if ($query->baoxiao_time) {
                                $time = $query->baoxiao_time;
                            } else {
                                $time = $query->settlement_time;
                            }
                            $query->jiesuan_time_one      = '本单已于'.date('Y-m-d', $time).'完成首次结算'.$money.'元。';
                            $where['level']               = $level;
                            $where['status']              = 0;
                            $money                        = OrderMore::where($where)->order('id desc')->value('money');
                            $query->jiesuan_time_text_two = '本单将于'.date('Y-m-d',
                                    $query->two_js_time).'左右进行次月结算'.$money.'元。';
                        }
                    }
                }
            }
            if ($status == 4) {
                $query->baoxiao_msg_text = "";
            }
            if ($status == 6) {
                $query->order_status          = 6;
                $query->jiesuan_time_text_two = '';
            }
        });
        $this->success('ok', $data);
    }

    //订单列表
    public function dailiindex()
    {
        $status                     = input('status', '');
        $ids                        = input('ids', '');
        $where['user_id|parent_id'] = $ids;
        $where['is_agency']         = 2;
        if ($status >= 0) {
            $where['order_status'] = $status;
        }
        $query        = $this->model->where($where);
        $package_name = input('package_name');

        if ($package_name) {
            $query = $query->where(['packages.user_name' => ['like', '%'.$package_name.'%']]);
        }
        $shipping_phone = input('shipping_phone');
        if ($shipping_phone) {
            $query = $query->where(['shipping_phone' => $shipping_phone]);
        }
        $phone = input('phone');
        if ($phone) {
            $query = $query->where(['phone' => $phone]);
        }
        $shipping_contact = input('shipping_contact');
        if ($shipping_contact) {
            $query = $query->where(['shipping_contact' => $shipping_contact]);
        }
        $sta_time = input('sta_time');
        $end_time = input('end_time');

        if ($sta_time && $end_time) {
            $sta_time = strtotime($sta_time.' 00:00:01');
            $end_time = strtotime($end_time.' 23:59:59');
            $query    = $query->where('createtime', 'between time', [$sta_time, $end_time]);
        }
        $data = $query->with(['packages'])->order('id desc')->paginate();
        $this->success('ok', $data);
    }

    //办理套餐
    public function add()
    {
        $params   = $this->request->post();
        $validate = [
            ['id', 'require', '请传递套餐ID'],
            ['shipping_contact', 'require', '请填写办卡人姓名'],
            ['agid', 'require', '缺少参数'],
            ['shipping_phone', 'require|regex:/^1\d{10}$/', '请输入把卡人手机号|办卡人手机号格式不对'],
            //            ['shipping_idcard', 'require|regex:/^\d{17}[0-9xX]$/', '请输入办理人身份证|身份证号格式错误'],
            ['shipping_province', 'require', '请选择收货人省份'],
            ['shipping_city', 'require', '请选择收货人城市'],
            ['shipping_area', 'require', '请选择收货人地区'],
            ['shipping_address', 'require', '请输入收货人详情地址']
        ];
        $result   = $this->validate($params, $validate);
        if ($result !== true) {
            $this->error($result);
        }
        $packagesInfo = Packages::where(['id' => $params['id']])->find();
        if (!$packagesInfo) {
            $this->error('产品不存在');
        }
        if ($packagesInfo['status'] != 1) {
            $this->error('产品已下架');
        }
        $UserInfo = \app\common\model\User::where(['id' => $params['agid']])->find();
        if (!$UserInfo) {
            $this->error('代理不存在');
        }
        $params['id']      = $packagesInfo['packages_id'];
        $data['appid']     = db('config')->where(['name' => 'ooen_appid'])->value('value');
        $data['timestamp'] = time();
        $data['nonce_str'] = Random::alnum(32);
        $data              = array_merge($data, $params);
        $string            = ascll($data);
        $open_appsecret    = db('config')->where(['name' => 'open_appsecret'])->value('value');
        $stringSignTemp    = $string.'&appsecret='.$open_appsecret;
        $data['sign']      = mb_strtoupper(md5($stringSignTemp));
        $url               = "http://agent.haoka.bx10086.cn/v1/haoka_api/packageOrder";//办理套餐
        $res               = httpPost($url, $data);
        $arr               = json_decode($res, true);
        if (!empty($arr['errcode'])) {
            $this->error($arr['errmsg']);
        }
//        $arr['errcode']  = 0;
//        $arr['order_id'] = time();
        if ($arr['errcode'] == 0) {
            $params['user_id']      = $UserInfo['id'];
            $params['goods_id']     = $packagesInfo['id'];
            $params['order_id']     = $arr['order_id'];
            $params['package_name'] = $packagesInfo['name'];
            $params['parent_id']    = $UserInfo['parent_id'];
            $params['two_id']       = $UserInfo['two_id'];
            $params['user_rebate']  = UserPackagesConfig::where([
                    'user_id'     => $params['agid'],
                    'packages_id' => $packagesInfo['id']
                ])->value('money') ?? 0;
            $params['is_agency']    = 2;
            $params['is_more']      = 1;
            unset($params['id'], $params['agid']);
            if (!empty($packagesInfo['duoci'])) {
                $arr = json_decode($packagesInfo['duoci'], true);
                if (!empty($arr[0])) {
                    $params['is_more'] = 2;
                }
            }
            $params['agency_area_id'] = 0;
            $cityAgency               = db('agency')->where(['area' => $params['shipping_area'], 'type' => 2])->find();
            if ($cityAgency) {
                $params['agency_area_id'] = $cityAgency['user_id'];
            }
            $params['plot_id'] = 0;
            $plotAgency        = db('agency')->where([
                'area'    => $params['shipping_area'],
                'address' => $params['plot'],
                'type'    => 1
            ])->find();
            if ($plotAgency) {
                $params['plot_id'] = $plotAgency['user_id'];
            }
            $params['is_verification'] = $packagesInfo['is_verification'];
            $r                         = $this->model->create($params);
            if ($r) {
//                if ($params['is_more'] == 2) {
                $order_id          = $r->id;
                $inser['order_id'] = $order_id;
                $inser['goods_id'] = $packagesInfo['id'];
                $inser['user_id']  = $UserInfo['id'];
                $inser['money']    = $params['is_more'] == 1 ? $packagesInfo['one_commission'] : $arr[0]['zigou'];
                OrderMore::create($inser);
                if ($params['parent_id'] > 0 && $arr[0]['one']) {
                    $inser['user_id'] = $params['parent_id'];
                    $inser['money']   = $params['is_more'] == 1 ? $packagesInfo['junior_contribution'] : $arr[0]['one'];
                    $inser['level']   = 2;
                    OrderMore::create($inser);
                }
//                        if ($params['two_id'] > 0 && $arr[0]['two']) {
//                            $inser['user_id']  = $params['two_id'];
//                            $inser['money']    = $params['is_more']==1?$packagesInfo['junior_contribution_tow']:$arr[0]['two'];
//                            $inser['level']    = 3;
//                            OrderMore::create($inser);
//                        }
                if ($params['agency_area_id'] && $arr[0]['area']) {
                    $inser['user_id'] = $params['agency_area_id'];
                    $inser['money']   = $params['is_more'] == 1 ? $packagesInfo['pplots_profit'] : $arr[0]['area'];
                    $inser['level']   = 4;
                    OrderMore::create($inser);
                }
                if ($params['plot_id'] && $arr[0]['xiaoqu']) {
                    $inser['user_id'] = $params['plot_id'];
                    $inser['money']   = $params['is_more'] == 1 ? $packagesInfo['pplots_yunying_profit'] : $arr[0]['xiaoqu'];
                    $inser['level']   = 5;
                    OrderMore::create($inser);
                }
//                }
            }
        }
        $this->success('申领成功');
    }


    public function orderSync()
    {
        $params   = $this->request->post();
        $validate = [
            ['cardType', 'require', '请传递套餐ID'],
            ['provinceName', 'require', '请填写办卡人姓名'],
            ['provinceName', 'require', '缺少参数1'],
            ['cityName', 'require', '缺少参数2'],
            //            ['number', 'require', '缺少参数'],
            ['agid', 'require', '缺少参数3'],
            ['certName', 'require', '缺少参数4'],
            ['certNo', 'require', '缺少参数5'],
            ['postProvinceName', 'require', '缺少参数6'],
            ['postCityName', 'require', '缺少参数7'],
            ['postDistrictName', 'require', '缺少参数8'],
            //            ['postAddr', 'require', '缺少参数9'],
            ['contactNum', 'require', '缺少参数']
        ];
        $result   = $this->validate($params, $validate);
        if ($result !== true) {
            $this->error($result);
        }
        $params['postAddr'] = $params['shipping_address'];
        if (!$params['postAddr']) {
            $this->error('缺少地址');
        }
        $info = Packages::where(['id' => $params['cardType'], 'status' => 1])->find();
        if (!$info) {
            $this->error('产品不存在或已下架');
        }
        $UserInfo = \app\common\model\User::where(['id' => $params['agid']])->find();
        if (!$UserInfo) {
            $this->error('代理不存在');
        }

        if (empty($params['number'])) {
            $params['number'] = '';
        }
        if ($info['platform_type'] == 2) {
            $params['partnerId'] = '33587';
            $secret              = "kIVgqdLiNGYP3GeM";
            $url                 = "http://hao.san-jk.com/orderSync";
        } elseif ($info['platform_type'] == 3) {
            $params['partnerId'] = '25017';
            $secret              = "lQiUQJsnOqIaBqoU";
            $url                 = "http://haoka.zhnxu.com/orderSync";
        } elseif ($info['platform_type'] == 4) {
            $this->addorder172($info, $params, $UserInfo);
        } elseif ($info['platform_type'] == 6) {
            $this->kgjcreateOrder($info, $params, $UserInfo);
        }elseif ($info['platform_type'] == 7) {
            $this->self_help($info, $params, $UserInfo);
        }
        $params['postProvinceName'] = str_replace('省', '', $params['postProvinceName']);
        $params['provinceName']     = str_replace('省', '', $params['provinceName']);

        if ($params['cityName'] == "市辖区" || $params['cityName'] == "县") {
            $params['postCityName']     = $params['provinceName'];
            $params['postProvinceName'] = str_replace('市', '', $params['provinceName']);
        }
        if ($info['province_name']) {
            $params['provinceName'] = $info['province_name'];
        }
        if ($info['city_name']) {
            $params['cityName'] = $info['city_name'];//市
        }
        $params['cardType'] = (int)$info['packages_id'];
        ksort($params);//升序排序
        $str = '';
        foreach ($params as $k => $v) {
            $str .= $k.$v;
        }
        $str            = $secret.$str.$secret;  //abc123cardType4cityName郑州市pageNo1partnerId1proniceName河南searchValue4150222abc123
        $sign           = strtoupper(md5($str)); //93932E8BD15A2EBE6D0C4F3890B97D90
        $params['sign'] = $sign;
        if ($this->auth->id == 2) {
//            dump($params);exit();
        };
        $res = json_decode(httpPost($url, $params), true);
//        $res['data']['orderId'] = time();
        if (!empty($res['data']['orderId'])) {
            $this->model->orderCreateAdd($params, $UserInfo, $info, $res['data']['orderId']);
            $this->success('下单成功');
        }
        $this->error($res['info']);
    }

    public function purchase()
    {
        $ids  = input('ids');
        $info = Packages::where(['id' => $ids, 'status' => 1])->find();
        if (!$info) {
            $this->error('产品不存在或已下架');
        }
        $ask               = db('config')->where(['name' => 'gth_aes_key'])->value('value');
        $shareId           = db('config')->where(['name' => 'gth_share_id'])->value('value');
        $mobile            = $orderInser['shipping_phone'] = input('mobile'); //办卡人手机号
        $name              = $orderInser['shipping_contact'] = input('name'); //把卡人姓名
        $id_num            = $orderInser['shipping_idcard'] = input('id_num');//把卡人身份证号
        $data['share_id']  = $shareId;
        $data['sku']       = $info['user_name'];
        $data['source_id'] = time();
        $data['id_name']   = base64_encode(openssl_encrypt($name, 'aes-256-ecb', $ask, OPENSSL_RAW_DATA));
        $data['id_num']    = base64_encode(openssl_encrypt($id_num, 'aes-256-ecb', $ask, OPENSSL_RAW_DATA));
        $data['mobile']    = base64_encode(openssl_encrypt($mobile, 'aes-256-ecb', $ask, OPENSSL_RAW_DATA));
        $data['name']      = base64_encode(openssl_encrypt($name, 'aes-256-ecb', $ask, OPENSSL_RAW_DATA));
//        $data['province_code'] = input('province_code');
        $data['province	'] = $orderInser['shipping_province'] = input('province');
//        $data['city_code']     = input('city_code');
        $data['city'] = $orderInser['shipping_city'] = input('city');
//        $data['district_code']     = input('district_code');
        $data['district']    = $orderInser['shipping_area'] = input('district');
        $address             = $orderInser['shipping_area'] = input('address');
        $data['address']     = base64_encode(openssl_encrypt($address, 'aes-256-ecb', $ask, OPENSSL_RAW_DATA));
        $data['pic']['face'] = $this->request->file('face');
        $data['pic']['back'] = $this->request->file('back');
        $data['pic']['hand'] = $this->request->file('hand');
        $data['sign']        = $this->generateSignature($data);
        $url                 = "https://notify.91haoka.cn/api/plan-market/order/purchase/v2";//办理套餐
        dump($data);
        exit();
        $res = httpPost($url, $data);
        dump(json_decode($res, true));
        exit();
//        $this->success('',$res);


    }

    public function generateSignature($data)
    {
        // 初始化待加密的字符串

        $queryString = "share_id={$data['share_id']}&sku={$data['sku']}&source_id={$data['source_id']}";
        $apiToken    = db('config')->where(['name' => 'gth_api_token'])->value('value');
        // 追加api_token
        $queryString .= "{$apiToken}";
        // 使用MD5加密生成签名
        $signature = md5($queryString);
        return $signature;
    }

    /**
     * @menu 卡管家开卡
     * @Author:男人的坏
     * @Date:2024-04-19 07:14
     */
    public function kgjcreateOrder($goods, $params, $UserInfo)
    {
        $path                  = '/api/card/open/submitOrder';
        $key                   = db('config')->where(['name' => 'kgj_appkey'])->value('value');
        $kgj_aesSecret         = db('config')->where(['name' => 'kgj_aesSecret'])->value('value');
        $data['goodsCode']     = $goods['packages_id'];
        $data['cardName']      = kgjAsc($params['certName'], $kgj_aesSecret);//收货人
        $data['cardNo']        = kgjAsc($params['certNo'], $kgj_aesSecret);//身份证号
        $data['receiverName']  = kgjAsc($params['certName'], $kgj_aesSecret);//收货人
        $data['receiverPhone'] = kgjAsc($params['contactNum'], $kgj_aesSecret); //联系人话
        $data['province']      = $params['postProvinceName'];//省
        $data['city']          = $params['postCityName'];//市
        $data['county']        = $params['postDistrictName'];//区县
        $data['address']       = kgjAsc($params['postAddr'], $kgj_aesSecret);//详细地址
        $data['outTradeNo']    = $this->auth->id.time();
        $data['prePhone']      = input('number', '');
        $checkCode             = input('checkCode', '');
        if ($checkCode) {
            $data['checkCode'] = $checkCode;
        }
        $res = kgjcurl($path, $data,$key);
        if (!empty($res['data']['orderSn'])) {
            $params['outTradeNo'] = $data['outTradeNo'];
            $this->model->orderCreateAdd($params, $UserInfo, $goods, $res['data']['orderSn']);
            $this->success('申领成功');
        } else {
            $this->error('开卡失败：'.$res['msg']);
        }
    }

    /**
     * @menu 自助开卡
     * @Author:男人的坏
     * @Date:2024-04-19 07:14
     */
    public function self_help($goods, $params, $UserInfo)
    {
        if ($params['cityName'] == "市辖区" || $params['cityName'] == "县") {
            $params['postCityName']     = $params['provinceName'];
            $params['postProvinceName'] = str_replace('市', '', $params['provinceName']);
        }
        $this->model->orderCreateAdd($params, $UserInfo, $goods, $this->auth->id.time());
        $this->success('申领成功');
    }

    public function generateSortedMD5($data)
    {
        $secretKey = db('config')->where(['name' => 'kgj_appkey'])->value('value');
        // 过滤空字符串并按照key的值进行升序排列
        $filteredData = array_filter($data, function ($value) {
            return $value !== '';
        });
        ksort($filteredData);

        // 构建待加密的字符串
        $queryString = '';
        foreach ($filteredData as $key => $value) {
            $queryString .= $key.'='.$value;
        }

        // 追加秘钥
        $queryString .= $secretKey;

        // 使用MD5加密生成签名
        $signature = md5($queryString);

        return $signature;
    }

    //172下单
    public function addorder172($goods, $params, $UserInfo)
    {
        $url                 = db('config')->where(['name' => 'url_172'])->value('value');
        $key                 = db('config')->where(['name' => 'key_172'])->value('value');
        $user_id             = db('config')->where(['name' => 'zhanghao_172'])->value('value');
        $data['user_id']     = $user_id;
        $data['Timestamp']   = time();
        $data['Name']        = $params['certName'];        //姓名
        $data['Phone']       = $params['contactNum'];      //办卡人手机号
        $data['IDCard']      = $params['certNo'];          //身份证号
        $data['Province']    = $params['provinceName'];    //省
        $data['City']        = $params['postCityName'];    //市
        $data['Area']        = $params['postDistrictName'];//区县
        $data['Address']     = $params['postAddr'];        //详细地址
        $data['ProductID']   = $goods['packages_id'];
        $data['DownOrderID'] = 'z'.$this->auth->id.time();
        $data['ThirdPhone']  = '';
        $string              = ascll172($data);
        $data['user_sign']   = strtolower(md5($string.$key));
        $url                 = $url.'/api/order/ApiToOrder';
        $res                 = httpPost($url, $data);
        $arr                 = json_decode($res, true);
//        $arr = cache('pt172');
//        $arr['message'] = time();
//        $arr['code']    = 0;
        if (!empty($arr['message']) && $arr['code'] == 0) {
            $this->model->orderCreateAdd($params, $UserInfo, $goods, $arr['message']);
            $this->success('申领成功');
        } else {
            $this->error('开卡失败：'.$arr['message']);
        }
    }

    public function orderInfo()
    {
        $params            = input('post.');
        $data['appid']     = db('config')->where(['name' => 'ooen_appid'])->value('value');
        $data['timestamp'] = time();
        $data['nonce_str'] = Random::alnum(32);
        $data              = array_merge($data, $params);
        $string            = ascll($data);
        $stringSignTemp    = $string.'&appsecret='.db('config')->where(['name' => 'open_appsecret'])->value('value');
        $data['sign']      = mb_strtoupper(md5($stringSignTemp));
        $url               = "http://agent.haoka.bx10086.cn/v1/haoka_api/orders";//办理套餐
        $res               = httpPost($url, $data);
        $arr               = json_decode($res, true);
        $this->success('ok', $arr);
    }

    public function callback()
    {
        cache('callback', $_POST);
        if (!empty($_POST['order_id'])) {
            $order = db('order')->where(['order_id' => $_POST['order_id']])->find();
            if ($order) {
                $rows               = $_POST;
                $up['order_status'] = $rows['order_status'];
                if (strpos($rows['remark'], '已激活') !== false) {
                    $up['order_status'] = 1;
                }
                if (strpos($rows['remark'], '待归档') !== false) {
                    $up['order_status'] = 1;
                }
                if (strpos($rows['remark'], '充值') !== false) {
                    $up['order_status']   = 4;
                    $up['baoxiao_status'] = 1;
                    $up['audit_status']   = 2;
                    $up['jiesuan_time']   = time();
                }
                $up['order_info_json']   = json_encode($_POST, true);
                $up['order_status_text'] = $rows['order_status_text'];
                $up['rebate']            = $rows['rebate'];
                $up['channel']           = $rows['channel'];
                $up['remark']            = $rows['remark'];
                $up['package_name']      = $rows['package_name'];
                if (!empty($rows['shipping_no'])) {
                    $up['shipping_no'] = $rows['shipping_no'];
                }
                if (!empty($rows['shipping_company_name'])) {
                    $up['shipping_company_name'] = $rows['shipping_company_name'];
                }
                $up['is_recharged'] = $rows['is_recharged'];
                db('order')->where(['id' => $order['id']])->update($up);
            }
        }
    }

    public function callbackTwo()
    {
        cache('callbackTwo', file_get_contents('php://input'));
        $data = file_get_contents('php://input');
        $this->cse($data);
    }

    public function cse($data)
    {
        $data = json_decode($data, true);
        if ($data) {
            $orderInfo = \app\common\model\Order::where(['order_id' => $data['orderId']])->find();
            if (!empty($orderInfo['packages'])) {
                if ($orderInfo['packages']['platform_type'] == 2) {
                    $secret = "kIVgqdLiNGYP3GeM";
                } else {
                    $secret = "lQiUQJsnOqIaBqoU";
                }
            }
            $send_sign = $data['sign'];

            unset($data['sign']);

            ksort($data);//字典排序,升序排列
            $str = '';
            foreach ($data as $k => $vv) {
                $str .= $k.$vv;
            }
            $sign = strtoupper(md5($secret.$str.$secret));//签名
            if ($sign == $send_sign) {
                if (isset($data['state'])) {
                    if ($data['state'] == 0) {
                        $orderInfo->order_status = 3;
                    } else {
                        if ($data['state'] == 11) {
                            $orderInfo->order_status = 2;
                        } else {
                            if ($data['state'] == 1 || $data['state'] == 10) {
                                $orderInfo->order_status = 1;
                            } else {
                                if ($data['state'] == 6) {
                                    $orderInfo->baoxiao_status = 1;
                                    $orderInfo->order_status   = 4;
                                    $orderInfo->audit_status   = 2;
                                    $orderInfo->jiesuan_time   = time();
                                } else {
                                    if ($data['state'] == 4) {
                                        $orderInfo->order_status = 0;
                                    }
                                }
                            }
                        }
                    }
                }
                if (isset($data['number'])) {
                    $orderInfo->phone = $data['number'];
                }

                if (isset($data['wlCompany'])) {
                    $orderInfo->shipping_company_name = $data['wlCompany'];
                }
                if (isset($data['wlOrderid'])) {
                    $orderInfo->shipping_no = $data['wlOrderid'];
                }
                if (isset($data['createtime'])) {
                    $orderInfo->callback_time = strtotime($data['createtime']);
                }
                if (isset($data['lgtsId'])) {
                    $orderInfo->lgtsId = $data['lgtsId'];
                }
                if (isset($data['info'])) {
                    $orderInfo->remark = $data['info'];
                }
                if (isset($data['actime'])) {
                    $orderInfo->actime = $data['actime'];
                }

                $orderInfo->order_info_json = json_encode($data, true);
                $r                          = $orderInfo->save();
                if ($r) {
                    echo "更新成功";
                }
            } else {
                echo "签名失败";
            }
        }
    }

    public function lottmat()
    {

    }

    /**
     *信息
     */
    public function orderimage()
    {
        $image    = input('post.image');
        $imagetwo = input('post.imagetwo');
        $order_id = input('order_id');
        $phone    = input('phone');
        if (!$order_id || !Validate::regex($phone, "^1\d{10}$") || !$imagetwo || !$image) {
            $this->error('缺少参数');
        }
        $where     = ['id' => $order_id];
        $ordreInfo = $this->model->where($where)->find();
        if (!$ordreInfo) {
            $this->error('订单不存在');
        }

        if ($ordreInfo['audit_status'] == 1) {
            $this->error('请等待审核');
        }
        if ($ordreInfo['audit_status'] == 2) {
            $this->error('已经审核通过请勿重复上传');
        }
        $ordreInfo->audit_status      = 1;
        $ordreInfo->reason            = '';
        $ordreInfo->audit_upload_time = time();
        $ordreInfo->phone             = $phone;
        $ordreInfo->image             = $image;
        $ordreInfo->call_image        = $imagetwo;
        $ordreInfo->save();
        $this->success('提交成功');

    }

}
